<?php
/**
 * Search a Mission
 *
 * @author Xavier VILAIN
 *
 */
use Doctrine\DBAL\Connection;
use Hive\Mission;
use Fox\Html\CheckBox;
use Fox\Dao\SqlFragment;
use Fox\Generator;
use Fox\Html\Input;
use Fox\Html\Screen;
use Fox\Html\Anchor;
use Fox\SearchEngine;
// Init
$xview = Xview::instance();
$ajax = $xview->val("ajax",false);

$output = null;
// HTML Components
$screen = new Screen('eSearchMission','vlook');
$screen->toolbar()->add(new Fox\Html\Button('add','?mod=missions&act=create',Msg(Hive::BUNDLE,Hive::MISSION_ADD_NEW)));

$block = new Fox\Html\Block('BLOOK',Msg(Hive::BUNDLE,Hive::MISSION_SEARCH));
// Filters
$block->add(new Input('keyword',false));
$block->add(new CheckBox('status',false))->label(Msg(Hive::BUNDLE,Hive::MISSION_DISPLAY_CLOSED));
$screen->add($block);

$inputs = $screen->get();
if(!$screen->errors())
{
	$joins = null;
	$filters = array();
	if(!$inputs['status']) {
		$filters[] = new SqlFragment('status NOT IN (?) OR status IS NULL',array(array(Mission::STATUS_CLOSED)),
			array(Connection::PARAM_STR_ARRAY));
	}
	try {
		$result = array();
		if(empty($inputs['keyword']) && $screen->submitted())
		{
			$finder = new Hive\Mission();
			$result = $finder->find(SqlFragment::combine($filters),array('title' => 'ASC'),$joins,null,true);
			
		} elseif(empty($inputs['keyword'])) {
			$finder = new Hive\Mission();
			$id = User::current()->getId();
			$filters[] = new SqlFragment('( uname = ? OR cname = ? )',array($id,$id));
			$result = $finder->find(SqlFragment::combine($filters),array('udate' => 'DESC'),$joins,10,true);
		}
		else
		{
			$searchType[] = new Fox\Dao\SqlFragment('grouping_type = ?',array(Hive\Mission::className()));
			$searchEngine = new SearchEngine();
			$matches = $searchEngine->search(explode(' ',strtolower($inputs['keyword']))
												,SearchEngine::MODE_LIKE,
												$searchType);
			if(is_array($matches))
			{
				foreach($matches as $match)
				{
					switch ($match['reference_type'])
					{
						case Hive\Mission::classname() :
							$missionIds[] = $match['reference_id'];
							break;
						case Hive\Mission\Announce::classname() :
							$announceIds[] = $match['reference_id'];
							break;
					}
				}


				$fragments[Hive\Mission::classname()] = isset($missionIds) ?  new Fox\Dao\SqlFragment('t.missionid IN (?)',
														array($missionIds),
														array(Doctrine\DBAL\Connection::PARAM_STR_ARRAY)) : null;

				$fragments[Hive\Mission\Announce::classname()] = isset($announceIds) ?  new Fox\Dao\SqlFragment('announceid IN (?)  AND an.loekz = 0 ',
														array($announceIds),
														array(Doctrine\DBAL\Connection::PARAM_STR_ARRAY)) : null;
				$result = array();
				// Find Ressource
				$finder = new Hive\Mission();
				foreach($fragments as $type => $fragment)
				{
					if(empty($fragment))
						continue;
					$joins = null;
					// Add customs Filters
					$fragment = array($fragment,$filters);
					switch($type)
					{
						case Hive\Mission\Announce::classname();
							$joins[] = Hive\Mission::$JOIN_ANNOUNCES;
							break;
						case Hive\Mission::classname();
							break;

					}
					$resultTmp = $finder->find(Fox\Dao\SqlFragment::combine($fragment),array('title' => false),$joins);
					foreach($resultTmp as $object)
					{
						$result[$object->getId()] = $object;
					}
				}
				if(count($result) == 0){
					Fox\Message::Warning(Msg(Fox\Messages\SearchEngine::BUNDLE,Fox\Messages\SearchEngine::NO_DOCUMENT_FOUND));
				}
			}
			else
			{
				Fox\Message::Warning(Msg(Fox\Messages\SearchEngine::BUNDLE,Fox\Messages\SearchEngine::NO_DOCUMENT_FOUND));
			}

		}
		//---- Output View	----
		// Depending on the mode
		$data = null;
		$grid = new Fox\Grid("gMission",null,Msg(Fox::MSGCL,143,count($result)));
		$grid->fieldcat(array(array("company","companyName"),array("mission_reference","reference"),array("mission_description","description"),"jobtitle","start_date","uname","udate"));

		$grid->setFieldAttr(array("reference","companyName","jobtitle","description"),"setAnchor",
							new Anchor(Generator::url("missions","main"),array("missionid")));
		$grid->fieldcat()->field("companyName")->width(14);
		$grid->fieldcat()->field("reference")->width(20);
		$grid->fieldcat()->field("description")->width("30");
		foreach($result as $object)
		{
			$item = $object->getData();
			$item['missionid'] = $object->getId();
			$item['description'] = mb_substr($object->description,0,40,_CHARSET_)."...";
			/*
			$country = $ressource->address()->country;
			if(empty($country) || $country == 'fr')
			{
				$postal_code = substr($ressource->address()->postal_code,0,2);
				$adress = $ressource->address()->city;
				$adress .= empty($postal_code) ? null : ' ('.$postal_code.')';
			}
			else
			{
				$adress = \Fox\Ddic\DataElement\Text::label('country',$ressource->address()->country);
			}
			$item['adress'] = $adress;
			*/
			$data[] = $item;
		}

		$grid->initialize($data,true);
		if(count($data) == 0 && !$screen->submitted()) {
			
		} else {
			$output = $grid->Display();
		}
		
	}
	catch (Exception $e)
	{
		Fox\Message::Error($e->getMessage());
	}
}


if(!$ajax)
{
	echo $screen->display();
	echo '<div id="searchResult">'.$output.'</div>';
}
else
{
	echo Xview::instance()->messages();
	echo $output;
}